package top.hcode.hoj.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Strings;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.hcode.hoj.dao.CollQuestionDao;
import top.hcode.hoj.dao.CollQuestionOptionDao;
import top.hcode.hoj.pojo.dto.coll.AdmQueryCollQuestionOptionDTO;
import top.hcode.hoj.pojo.dto.coll.AdmSaveCollQuestionOptionsDTO;
import top.hcode.hoj.pojo.entity.coll.CollQuestion;
import top.hcode.hoj.pojo.entity.coll.CollQuestionOption;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author orangej
 * @since 2025-02-09
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminCollQuestionOptionService {
    private final CollQuestionOptionDao optionDao;
    private final CollQuestionDao questionDao;

    public IPage<CollQuestionOption> getCollQuestionOptionList(AdmQueryCollQuestionOptionDTO form) {
        IPage<CollQuestionOption> pager = new Page<>(form.getCurrentPage(), form.getLimit());

        QueryWrapper<CollQuestionOption> query = new QueryWrapper<>();
        if (Strings.isNotBlank(form.getQuestionId())) {
            query.eq("question_id", form.getQuestionId());
        }
        query.orderByAsc("sort_order");
        optionDao.page(pager, query);
        return pager;
    }

    @Transactional
    public List<CollQuestionOption> saveCollQuestionOption(AdmSaveCollQuestionOptionsDTO form) {
        String questionId = form.getQuestionId();
        CollQuestion question = questionDao.getById(questionId);
        if (question == null) {
            throw new IllegalArgumentException("题目不存在 : " + questionId);
        }

        String collId = question.getCollId();

        List<CollQuestionOption> optionList = form.getOptionList();
        for (CollQuestionOption option : optionList) {
            if (option.getId() == null) {
                option.setCollId(collId);
                option.setQuestionId(questionId);
            }
            option.setQuestionId(questionId);
            optionDao.saveOrUpdate(option);
        }

        List<String> optionIdList = optionList.stream().map(CollQuestionOption::getId).collect(Collectors.toList());

        optionDao.removeOtherOptions(questionId, optionIdList);
        return optionList;
    }

    public void deleteCollQuestionOption(Long id) {
        optionDao.removeById(id);
    }
}
